package org.myxdb.server.message;

import java.util.Map;

import org.apache.xmlrpc.XmlRpcHandler;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.XmlRpcRequest;

import org.myxdb.server.message.*;
import org.xmldb.api.base.XMLDBException;

public final class MessageInterface implements XmlRpcHandler{

	public static final String MESSAGE_PARAM = "message";
	
	private static final XmlRpcHandler INSTANCE = new MessageInterface();

	public static XmlRpcHandler getHandler() {
        return INSTANCE;
    }
	 
	private MessageInterface() 
	{	    
		
	}
	
	 public Object execute(XmlRpcRequest xmlRpcRequest) throws XmlRpcException 
	 {
	        Map message = (Map) xmlRpcRequest.getParameter(0);
	       
	        // The method determines what class we load to handle the message.
	        String type = (String) message.get(MESSAGE_PARAM);	              
				try {
					 RPCMessage handler = (RPCMessage) Class.forName("org.myxdb.server.message." + type).newInstance();        
			            return handler.execute(message);
				} catch (InstantiationException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return null;
	 	}
}
